const path = require('path')
const Koa = require('koa')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const Manager = require('./core/manager')
const app = new Koa()

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'

async function start () {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 3000
  } = nuxt.options.server

  await nuxt.ready()
  // Build in development
  if (config.dev&&process.env.NODE_ENV!="test") {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  new Manager(app)
    .initBodyParser()
    .initException()
    .initRouter(path.resolve(__dirname, './api/v1'))
  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })
  if(require.main === module){
    app.listen(port)
  }
  console.log("---------------------")
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
  return app
}

if(require.main !== module){
  module.exports=async()=>{
    return await start()
  }
}
else {
  start()
}

